package com.stylefeng.guns.rest.modular.wz.api.v3.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.api.v3.dao.WzCouponDaoImpl;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzMapActivityService;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzFinanceService;
import com.stylefeng.guns.rest.modular.wz.service.IPfFileService;
import com.stylefeng.guns.rest.modular.wz.service.IWzPrizeService;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.stylefeng.guns.rest.enums.EnWzPrize.COUPON_STATUS_USED;

/**
 * 提现页面业务层
 */
@Service
public class WzUserActivityServiceImpl {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private WzMapActivityMapper mapActivityMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private IWzMapActivityService mapActivityService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzCouponDaoImpl couponDao;
    @Autowired
    private WzCouponOrderMapper couponOrderMapper;
    @Autowired
    private WzUserActivityMapper userActivityMapper;
    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private IWzPrizeService prizeService;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzCouponMarketMapper couponMarketMapper;
    @Autowired
    private WzUserMergeDetailMapper userMergeDetailMapper;
    @Autowired
    private WzUserRebateMapper userRebateMapper;



    public Res myAdvMapList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = advMapMapper.selectCount(new EntityWrapper<WzAdvMap>().eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).eq("user_code", userCode).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex(), EnWzAdvMap.STATUS_Checking.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);
        int finishNumber = advMapMapper.selectCount(new EntityWrapper<WzAdvMap>().eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).eq("user_code", userCode).eq("status", EnWzAdvMap.STATUS_Expired.getIndex()));
        paramMap.put("finishNumber", finishNumber);
        //店铺
        EntityWrapper<WzAdvMap> e = new EntityWrapper<WzAdvMap>();
        e.eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).eq("user_code", userCode);
        if (status == 1) {//发布中
            e.in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex(), EnWzAdvMap.STATUS_Checking.getIndex(), EnWzAdvMap.STATUS_Add_Reject.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzAdvMap.STATUS_Expired.getIndex());
        }
        String sql = "ad_code As adCode,end_time AS endTime,reject_remark As rejectRemark,end_time AS endTime,target_id As targetId,adv_map_id AS advMapId,user_code AS userCode,subtype,logo,avatar_url AS avatarUrl,subtitle,name,status,share_link As shareLink,merchant_tel As merchantTel,longitude,latitude,merchant_full_address As merchantFullAddress,daily_amount As dailyAmount";
        List<Map<String, Object>> advMapList = advMapMapper.selectMaps(e.setSqlSelect(sql));
        //修改中处理
        for (Map<String, Object> map : advMapList) {
            if (StringUtils.isNotBlank(map.get("targetId").toString())) {
                Long targetId = Long.parseLong(map.get("targetId").toString());
                WzAdvMap targetAdvMap = advMapMapper.selectById(targetId);
                map.put("name", targetAdvMap.getName());
                map.put("logo", targetAdvMap.getLogo());
                map.put("avatarUrl", targetAdvMap.getAvatarUrl());
                map.put("subtitle", targetAdvMap.getSubtitle());
                map.put("shareLink", targetAdvMap.getShareLink());
                map.put("merchantTel", targetAdvMap.getMerchantTel());
                map.put("longitude", targetAdvMap.getLongitude());
                map.put("latitude", targetAdvMap.getLatitude());
                map.put("merchantFullAddress", targetAdvMap.getMerchantFullAddress());
            }
            map.remove("targetId");
        }
        paramMap.put("list", advMapList);
        return Res.success(paramMap);
    }

    public Res myAdvMapActivityList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = mapActivityMapper.selectCount(new EntityWrapper<WzMapActivity>().eq("user_code", userCode).in("status", new Integer[]{EnWzMapActivity.STATUS_RELEASE.getIndex(), EnWzMapActivity.STATUS_CHECKING.getIndex(), EnWzMapActivity.STATUS_REJECT.getIndex(),EnWzMapActivity.STATUS_End.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = mapActivityMapper.selectCount(new EntityWrapper<WzMapActivity>().eq("user_code", userCode).eq("status", EnWzMapActivity.STATUS_Expired.getIndex()));
        paramMap.put("finishNumber", finishNumber);//完成/过期
        //活动
        EntityWrapper<WzMapActivity> e = new EntityWrapper<WzMapActivity>();
        e.eq("user_code", userCode);
        if (status == 1) {//发布中
            e.in("status", new Integer[]{EnWzMapActivity.STATUS_RELEASE.getIndex(), EnWzMapActivity.STATUS_CHECKING.getIndex(), EnWzMapActivity.STATUS_REJECT.getIndex(),EnWzMapActivity.STATUS_End.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzMapActivity.STATUS_Expired.getIndex());
        }
        String sql = "reject_remark As rejectRemark,jointype,usetype,map_activity_id As mapActivityId,coupon_id AS couponId,adv_map_id AS advMapId,name,logo,need_share_number As needShareNumber,pic,subtype,benefit,join_number As joinNumber,total_number As totalNumber,status,begin_time As beginTime,end_time AS endTime";
        List<Map<String, Object>> advMapActivityList = mapActivityMapper.selectMaps(e.setSqlSelect(sql));
        for(Map<String, Object> map:advMapActivityList){
            Map<String, Object> coupon = cacheService.couponData(Long.parseLong(map.get("couponId").toString()));
            map.put("rule",coupon.get("rule"));
            map.put("couponType",coupon.get("type"));
            map.put("couponBeginTime",coupon.get("beginTime"));
            map.put("couponEndTime",coupon.get("endTime"));
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(map.get("advMapId").toString()));
            map.put("advMapEndTime",advMap.getEndTime());
            map.put("longitude",advMap.getLongitude());
            map.put("latitude",advMap.getLatitude());
        }
        paramMap.put("list", advMapActivityList);
        return Res.success(paramMap);
    }

    public Res myAdvMapAdvList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = advMapper.selectCount(new EntityWrapper<WzAdv>().eq("user_code", userCode).in("status", new Integer[]{EnWzAdv.STATUS_RELEASE_no.getIndex(), EnWzAdv.STATUS_RELEASE_yes.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = advMapper.selectCount(new EntityWrapper<WzAdv>().eq("user_code", userCode).eq("status", EnWzAdv.STATUS_Settlement.getIndex()).in("subtype", new Integer[]{EnWzAdv.SUBTYPE_ADV.getIndex(), EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()}));
        paramMap.put("finishNumber", finishNumber);//过期
        //广告红包
        EntityWrapper<WzAdv> e = new EntityWrapper<WzAdv>();
        e.eq("user_code", userCode).in("subtype", new Integer[]{EnWzAdv.SUBTYPE_ADV.getIndex(), EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()}).orderBy("release_time",false);
        if (status == 1) {//发布中
            e.in("status", new Integer[]{EnWzAdv.STATUS_RELEASE_no.getIndex(), EnWzAdv.STATUS_RELEASE_yes.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzAdv.STATUS_Settlement.getIndex());
        }
        String sql = "screen_city As screenCity,share_reward As shareReward,share_average_reward As shareAverageReward,adv_id As advId,adv_map_id As advMapId,title,avatar_url As logo,nick_name As name,cover_url As coverUrl,subtype,status,total_number As totalNumber,push_number As pushNumber,begin_time As beginTime,end_time As endTime";
        List<Map<String, Object>> advList = advMapper.selectMaps(e.setSqlSelect(sql));

        for (Map<String, Object> map : advList) {
            //参与分享人数
            int shareNumber = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",map.get("advId")));
            map.put("shareNumber",shareNumber);
            //可参与分享总人数
            if(Integer.parseInt(map.get("shareAverageReward").toString()) == 0){
                map.put("shareUserNumber",0);
            }else{
                map.put("shareUserNumber",Integer.parseInt(map.get("shareReward").toString())/Integer.parseInt(map.get("shareAverageReward").toString()));
            }
            if (!map.get("logo").toString().substring(0, 4).equals("http")) {
                map.put("logo", "http://oss.50waizhuan.com/" + map.get("logo"));
            }
            map.put("totalshareNumber", "0");//有效点击数
            map.put("totalclickNumber", "0");//总点击数
            List<Map<String, Object>> totalshareNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id", Long.parseLong(map.get("advId").toString())));
            List<Map<String, Object>> totalclickNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(click_number) As totalclickNumber").eq("adv_id", Long.parseLong(map.get("advId").toString())));
            if (totalshareNumber.get(0) != null) {
                map.put("totalshareNumber", Integer.parseInt(totalshareNumber.get(0).get("totalshareNumber").toString()) + Integer.parseInt(map.get("pushNumber").toString()));
            }
            if (totalclickNumber.get(0) != null) {
                map.put("totalclickNumber", Integer.parseInt(totalclickNumber.get(0).get("totalclickNumber").toString()) + Integer.parseInt(map.get("pushNumber").toString()));
            }
        }
        paramMap.put("list", advList);
        return Res.success(paramMap);
    }

    public Res myAdvMapCouponList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = couponMapper.selectCount(new EntityWrapper<WzCoupon>().eq("user_code", userCode).in("status", new Integer[]{EnWzPrize.COUPON_STATUS_WaitCheck.getIndex(), EnWzPrize.COUPON_STATUS_Reject.getIndex(), EnWzPrize.COUPON_STATUS_Release.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = couponMapper.selectCount(new EntityWrapper<WzCoupon>().eq("user_code", userCode).eq("status", EnWzPrize.COUPON_STATUS_End.getIndex()));
        paramMap.put("finishNumber", finishNumber);//过期
        //广告红包
        EntityWrapper<WzCoupon> e = new EntityWrapper<WzCoupon>();
        e.eq("user_code", userCode);
        if (status == 1) {//进行中
            e.in("status", new Integer[]{EnWzPrize.COUPON_STATUS_WaitCheck.getIndex(), EnWzPrize.COUPON_STATUS_Reject.getIndex(), EnWzPrize.COUPON_STATUS_Release.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzPrize.COUPON_STATUS_End.getIndex());
        }
        String sql = "price,stock,reject_remark As rejectRemark,type,coupon_id As couponId,adv_map_id As advMapId,benefit,pic,rule,subtype,status,begin_time As beginTime,end_time As endTime,prize_id As prizeId";

        List<Map<String, Object>> couponList = couponMapper.selectMaps(e.setSqlSelect(sql).eq("user_code", userCode));
        for (Map<String, Object> map : couponList) {
            if(StringUtils.isNotBlank(map.get("prizeId").toString())){
                WzPrize prize=prizeService.selectById(map.get("prizeId").toString());
                map.put("prizeStock",prize.getStock());//抽奖券库存
                map.put("prizeQuantity",prize.getQuantity());//抽奖券总数
            }else{
                map.put("prizeStock","");
                map.put("prizeQuantity","");
            }
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(map.get("advMapId").toString()));
            map.put("logo", advMap.getLogo());
            map.put("name", advMap.getName());
            map.put("longitude",advMap.getLongitude());
            map.put("latitude",advMap.getLatitude());
            map.put("merchantTel",advMap.getMerchantTel());
            map.put("advMapEndTime",advMap.getEndTime());
            //已卖出数量
            List<Object> soldNumber = couponOrderMapper.selectObjs(new EntityWrapper<WzCouponOrder>().setSqlSelect("ifnull(sum(order_number),0)").eq("coupon_id", map.get("couponId").toString()));
            map.put("soldNumber", soldNumber.get(0));
            //通过活动获取券的数量
            int getNubmer=userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("coupon_id", Long.parseLong(map.get("couponId").toString())));
            map.put("getNumber",getNubmer);

            int usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("coupon_id", Long.parseLong(map.get("couponId").toString())).eq("status", EnWzPrize.COUPON_STATUS_USED.getIndex()));//销量
            map.put("usedNumber", usedNumber);
        }
        paramMap.put("list", couponList);
        return Res.success(paramMap);
    }

    @Transactional
    public Res addMapActivity(ParamMap paramMap) throws Exception{
        //活动参数
        Long advMapId = paramMap.getLongMisValid("advMapId");//周边店铺id
        int needShareNumber = paramMap.getIntMisValid("needShareNumber");//需要分享人数
        int usetype = paramMap.getIntMisValid("usetype");//活动限制:1-限每人每天可领一次；2-限每人只可领一次；
        int totalNumber = paramMap.getIntMisValid("totalNumber");//活动总数量
        int jointype = paramMap.getIntMisValid("jointype");//活动类型：1-直接参与；2-扫码参与；
        String beginTimeZ = paramMap.getStrMisValid("activityBeginTime");//活动开始时间
        Date activityBeginTime = DateUtil.toDateTime(beginTimeZ + " 00:00:00");
        String endTimeZ = paramMap.getStrMisValid("activityEndTime");//活动结束时间
        Date activityEndTime = DateUtil.toDateTime(endTimeZ + " 23:59:59");
        int amount = paramMap.getIntMisValid("amount");//费用
        //新增活动
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);//发布用户
        WzMapActivity mapActivity = new WzMapActivity();
        WzAdvMap advMap = advMapMapper.selectById(advMapId);
        mapActivity.setAdCode(advMap.getAdCode());
        mapActivity.setMapActivityId(IdWorker.getId());
        mapActivity.setLogo(advMap.getLogo());
        mapActivity.setName(advMap.getName());
        mapActivity.setAdvMapId(advMapId);
        mapActivity.setUserCode(userCode);
        mapActivity.setTotalNumber(totalNumber);
        mapActivity.setSurplusNumber(totalNumber);
        mapActivity.setNeedShareNumber(needShareNumber);
        mapActivity.setJointype(jointype);
        mapActivity.setUsetype(usetype);
        mapActivity.setCreateTime(new Date());
        mapActivity.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        mapActivity.setStatus(EnWzMapActivity.STATUS_CHECKING.getIndex());
        mapActivity.setBeginTime(activityBeginTime);
        mapActivity.setEndTime(activityEndTime);
        //新增券
        Long couponOrderId = paramMap.getLongValid("couponOrderId");//购买的券id
        if (couponOrderId == null) {//新增券
            //参数
            int subtype = paramMap.getIntMisValid("subtype");//子类型：1-优惠券；2-兑换券
            String benefit = paramMap.getStrMisValid("benefit");//优惠方案
            String rule = paramMap.getStr("rule");//规则
            //生成券
            WzCoupon coupon = new WzCoupon();
            if (subtype == EnWzMapActivity.SUBTYPE_DHQ.getIndex()) {
                String pic = paramMap.getStrMisValid("pic");
                mapActivity.setPic(pic);
                coupon.setPic(pic);
            }
            int expense = totalNumber * Integer.parseInt(Consts.activityCouponFee);
            if(expense != amount){
                return Res.fail("金额错误!");
            }
            if (user.getCashBalance() < expense) {
                return Res.fail("余额不足,请充值!");
            }
            String beginTimeX = paramMap.getStrMisValid("couponBeginTime");//礼券开始时间
            Date couponBeginTime = DateUtil.toDateTime(beginTimeX + " 00:00:00");
            String endTimeX = paramMap.getStrMisValid("couponEndTime");//礼券结束时间
            Date couponEndTime = DateUtil.toDateTime(endTimeX + " 23:59:59");
            if (activityEndTime.after(advMap.getEndTime())) {
                return Res.fail("活动结束时间必须在周边店铺结束时间之前！");
            }
            if (activityEndTime.after(couponEndTime)) {
                return Res.fail("活动结束时间必须在礼券结束时间之前！");
            }
            coupon.setCouponId(IdWorker.getId());
            coupon.setAdvMapId(advMapId.toString());
            coupon.setStock(totalNumber);
            coupon.setUserCode(mapActivity.getUserCode());
            coupon.setBeginTime(couponBeginTime);
            coupon.setEndTime(couponEndTime);
            coupon.setRule(rule);
            coupon.setType(EnWzPrize.TYPE_Activity_Coupon.getIndex());//类型：活动券
            coupon.setSubtype(subtype);
            coupon.setCreateTime(new Date());
            coupon.setBenefit(benefit);
            //活动信息
            mapActivity.setCouponId(coupon.getCouponId());
            mapActivity.setBenefit(benefit);
            mapActivity.setSubtype(subtype);
            boolean r = financeService.addMapActivity(expense,mapActivity, coupon,user);
            if (r) {
                return Res.success();
            } else {
                return Res.fail();
            }
        } else {//购买的券
            WzCouponOrder couponOrder = couponOrderMapper.selectById(couponOrderId);//购买的券
            WzCoupon coupon = couponMapper.selectById(couponOrder.getCouponId());//券
            if (amount != 0) {
                return Res.fail("不需要付费!");
            }
            Date couponEndTime = coupon.getEndTime();
            //剩余数量
            if ((couponOrder.getOrderNumber() - couponOrder.getUsedNumber()) < totalNumber) {
                return Res.fail("优惠券库存不足!");
            }
            if (activityEndTime.after(advMap.getEndTime())) {
                return Res.fail("活动结束时间必须在周边店铺结束时间之前！");
            }
            if (activityEndTime.after(couponEndTime)) {
                return Res.fail("活动结束时间必须在礼券结束时间之前！");
            }
            couponOrder.setUsedNumber(couponOrder.getUsedNumber() + totalNumber);
            if(couponOrder.getUsedNumber()==couponOrder.getOrderNumber()){
                couponOrder.setStatus(2);//已用完
            }
            if (coupon.getSubtype() == EnWzMapActivity.SUBTYPE_DHQ.getIndex()) {
                String pic = coupon.getPic();
                mapActivity.setPic(pic);
            }
            mapActivity.setCouponId(coupon.getCouponId());
            mapActivity.setBenefit(coupon.getBenefit());
            mapActivity.setSubtype(coupon.getSubtype());
            boolean r = couponDao.addMapActivityUsedCoupon(mapActivity, couponOrder);
            if (r) {
                if (Consts.dev.equals("false")) {
                    String[] tel = new String[]{"15206121566", "17751585858"};
                    for (String c : tel) {
                        SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有新增活动需要审核", Consts.ADMIN_TEMPLATE_CODE);
                    }
                }
                return Res.success();
            } else {
                return Res.fail();
            }
        }
    }

    public Res editWzCoupon(ParamMap paramMap) throws Exception {
        Long couponId=paramMap.getLongMisValid("couponId");
        WzCoupon coupon=couponMapper.selectById(couponId);
        if(coupon.getStatus()!= EnWzPrize.STATUS_REJECT.getIndex()){
            return Res.fail("当前状态无法修改！");
        }
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int subtype = paramMap.getIntMisValid("subtype");//子类型：1-优惠券；2-兑换券;
        int stock = paramMap.getIntMisValid("stock");//数量
        String benefit = paramMap.getStrMisValid("benefit");//优惠方案
        String rule = paramMap.getStrMisValid("rule");//使用规则
        String beginTimeX = paramMap.getStrMisValid("beginTime");//礼券开始时间
        Date beginTime = DateUtil.toDateTime(beginTimeX + " 00:00:00");
        String endTimeX = paramMap.getStrMisValid("endTime");//礼券结束时间
        Date endTime = DateUtil.toDateTime(endTimeX + " 23:59:59");
        if (endTime.before(beginTime)) {
            return Res.fail("结束时间不能早于开始时间！");
        }
        int price = paramMap.getIntMisValid("price");//单价
        WzUser user = cacheService.user(userCode);//发布用户

        if (subtype == 2) {
            String previousPic = coupon.getPic();
            PfFile file = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_url", previousPic));
            if (file != null) {
                AliOssUtil.deleteObject(file.getFileUrl(), file.getType(), file.getBucketName());
                pfFileService.deleteById(file);
            }
            String pic = paramMap.getStrMisValid("pic");//兑换物图片
            coupon.setPic(pic);
        }
        coupon.setSubtype(subtype);
        coupon.setPrice(price);
        coupon.setStock(stock);
        coupon.setBenefit(benefit);
        coupon.setRule(rule);
        coupon.setBeginTime(beginTime);
        coupon.setEndTime(endTime);
        coupon.setStatus(EnWzPrize.COUPON_STATUS_WaitCheck.getIndex());//审核中
        int r = couponMapper.updateById(coupon);
        if (r > 0) {
            if (Consts.dev.equals("false")) {
                String[] tel = new String[]{"15206121566", "17751585858"};
                for (String c : tel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有商城礼券修改需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        }else{
            return Res.fail();
        }
    }

    public Res addWzCoupon(ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int subtype = paramMap.getIntMisValid("subtype");//子类型：1-优惠券；2-兑换券;
        int stock = paramMap.getIntMisValid("stock");//数量
        Long advMapId = paramMap.getLongMisValid("advMapId");//店铺id
        String benefit = paramMap.getStrMisValid("benefit");//优惠方案
        String rule = paramMap.getStrMisValid("rule");//使用规则
        String beginTimeX = paramMap.getStrMisValid("beginTime");//礼券开始时间
        Date beginTime = DateUtil.toDateTime(beginTimeX + " 00:00:00");
        String endTimeX = paramMap.getStrMisValid("endTime");//礼券结束时间
        Date endTime = DateUtil.toDateTime(endTimeX + " 23:59:59");
        //advMap信息
        WzAdvMap advMap = cacheService.advMap(advMapId);
        if(beginTime.before(DateUtil.toDateTime(DateUtil.toString(new Date())+" 00:00:00"))){
            return Res.fail("开始时间不能早于今天！");
        }
        if (endTime.before(beginTime)) {
            return Res.fail("结束时间不能早于开始时间！");
        }
        if (endTime.after(advMap.getEndTime())) {
            return Res.fail("结束时间必须在周边店铺结束时间之前！");
        }

        int price = paramMap.getIntMisValid("price");//单价
        WzUser user = cacheService.user(userCode);//发布用户

        WzCoupon coupon = new WzCoupon();
        if (subtype == 2) {
            String pic = paramMap.getStrMisValid("pic");//兑换物图片
            coupon.setPic(pic);
        }
        coupon.setAdCode(advMap.getAdCode());
        coupon.setUserCode(userCode);
        coupon.setAdvMapId(advMapId.toString());
        coupon.setCouponId(IdWorker.getId());
        coupon.setType(EnWzPrize.TYPE_Shopping_Coupon.getIndex());//类型：商城券
        coupon.setSubtype(subtype);
        coupon.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        coupon.setPrice(price);
        coupon.setStock(stock);
        coupon.setBenefit(benefit);
        coupon.setRule(rule);
        coupon.setBeginTime(beginTime);
        coupon.setEndTime(endTime);
        coupon.setStatus(EnWzPrize.COUPON_STATUS_WaitCheck.getIndex());//审核中
        coupon.setCreateTime(new Date());
        boolean r = coupon.insert();
        if (r) {
            if (Consts.dev.equals("false")) {
                String[] tel = new String[]{"15206121566", "17751585858"};
                for (String c : tel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有商城礼券新增需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        }
        return Res.fail();
    }


    public Res couponList(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Integer advMapCategoryFirst = paramMap.getIntValid("advMapCategoryFirst");//0:全部
        EntityWrapper e = new EntityWrapper<WzCoupon>();
        if (advMapCategoryFirst != 0) {
            e.eq("adv_map_category_first", advMapCategoryFirst);
        }
        String sql = "coupon_id As couponId,adv_map_category_first As advMapCategoryFirst,user_code As userCode,adv_map_id As advMapId,price,stock,begin_time As beginTime,end_time As endTime,rule,subtype,benefit,pic";
        List<Map<String, Object>> couponList = couponMapper.selectMapsPage(new Page<>(pageNum, pageSize), e.setSqlSelect(sql).eq("status", EnWzPrize.COUPON_STATUS_Release.getIndex()));
        List<Map<String, Object>> data = new ArrayList<>();
        for (Map map : couponList) {
            //已卖出数量
            List<Object> soldNumber = couponOrderMapper.selectObjs(new EntityWrapper<WzCouponOrder>().setSqlSelect("ifnull(sum(order_number),0)").eq("coupon_id", map.get("couponId").toString()));
            if (Integer.parseInt(soldNumber.get(0).toString()) < Integer.parseInt(map.get("stock").toString())) {
                WzAdvMap advMap = cacheService.advMap(Long.parseLong(map.get("advMapId").toString()));
                map.put("latitude",advMap.getLatitude());
                map.put("longitude",advMap.getLongitude());
                map.put("name", advMap.getName());
                map.put("logo", advMap.getLogo());
                map.put("soldNumber", soldNumber.get(0));
                data.add(map);
            }
        }
        return Res.success(paramMap.data(data));
    }


    public Res buyCoupon(ParamMap paramMap) {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);//发布用户
        Long couponId = paramMap.getLongValid("couponId");
        WzCoupon coupon = couponMapper.selectById(couponId);
        //订单数量
        int orderNumber = paramMap.getIntMisValid("orderNumber");
        //总金额
        int totalAmountX = paramMap.getIntMisValid("totalAmount");
        int subtype = coupon.getSubtype();
        int price = coupon.getPrice();
        int totalAmount = 0;
        //优惠券
        if (price < Integer.parseInt(Consts.couponMiddleFee)) {
            totalAmount = (price + Integer.parseInt(Consts.lessCouponMiddleFee)) * orderNumber;
        } else {
            //单价 进一
            Double unitPrices = price * (1 + Double.parseDouble(Consts.moreCouponMiddleFee) / 100);
            int unitPrice = (int) Math.ceil(unitPrices);
            totalAmount = unitPrice * orderNumber;
        }

        if (totalAmount != totalAmountX) {
            return Res.fail("金额异常！");
        }
        if (user.getCashBalance() < totalAmount) {
            return Res.fail("余额不足,请充值!");
        }
        //已卖出数量
        List<Object> saledNumber = couponOrderMapper.selectObjs(new EntityWrapper<WzCouponOrder>().setSqlSelect("ifnull(sum(order_number),0)").eq("coupon_id", couponId));
        //剩余
        int remain = coupon.getStock() - Integer.parseInt(saledNumber.get(0).toString());
        if (orderNumber > remain) {
            return Res.fail("库存不足！仅剩" + remain + "张！");
        }

        //新增记录
        WzCouponOrder co = new WzCouponOrder();
        co.setUserCode(userCode);
        co.setCouponId(couponId);
        WzCouponOrder couponOrder = couponOrderMapper.selectOne(co);
        if (couponOrder == null) {
            co.setNickName(user.getNickName());
            String avatarurl = user.getAvatarUrl();
            if (!avatarurl.startsWith("http")) {
                avatarurl = Consts.DOMAIN + user.getAvatarUrl();
            }
            co.setAvatarUrl(avatarurl);
            co.setUserCode(userCode);
            co.setCouponId(couponId);
            co.setOrderNumber(orderNumber);
            co.setUsedNumber(0);//使用数
            co.setStatus(1);//状态：可使用
            co.setCreateTime(new Date());
            boolean r = financeService.buyCoupon(totalAmount,co,user,1);
            if (r) {
                return Res.success();
            }
        }else{
            couponOrder.setOrderNumber(couponOrder.getOrderNumber()+orderNumber);
            couponOrder.setStatus(1);//状态：可使用
            boolean r = financeService.buyCoupon(totalAmount,couponOrder,user,2);
            if (r) {
                return Res.success();
            }
        }

        return Res.fail();


    }

    public Res myCouponList(ParamMap paramMap) {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int status = paramMap.getIntMisValid("status");//状态:1-可使用；2-结束
        EntityWrapper e = new EntityWrapper<WzCoupon>();
        if (status == 1) {
            e.eq("status", status);
        } else {
            e.ne("status", 1);
        }
        e.setSqlSelect("coupon_order_id As couponOrderId ,coupon_id As couponId,order_number As orderNumber,used_number As usedNumber,status");
        List<Map<String, Object>> couponOrderList = couponOrderMapper.selectMapsPage(new Page<>(pageNum, pageSize), e.eq("user_code", userCode).eq("status", EnWzPrize.COUPONORDER_STATUS_NORMAL.getIndex()));
        for (Map couponOrder : couponOrderList) {
            //礼券信息
            WzCoupon coupon = couponMapper.selectById(couponOrder.get("couponId").toString());
            couponOrder.put("pic", coupon.getPic());
            couponOrder.put("beginTime", coupon.getBeginTime());
            couponOrder.put("endTime", coupon.getEndTime());
            couponOrder.put("rule", coupon.getRule());
            couponOrder.put("subtype", coupon.getSubtype());
            couponOrder.put("benefit", coupon.getBenefit());
            couponOrder.put("price", coupon.getPrice());

            //地图信息
            WzAdvMap advMap = advMapMapper.selectById(coupon.getAdvMapId());
            couponOrder.put("name", advMap.getName());
            couponOrder.put("logo", advMap.getLogo());
            couponOrder.put("longitude", advMap.getLongitude());
            couponOrder.put("latitude", advMap.getLatitude());
            couponOrder.put("merchantTel", advMap.getMerchantTel());
        }
        return Res.success(paramMap.data(couponOrderList));
    }

    public Res mapActivityJoinList(ParamMap paramMap) {
        Long mapActivityId = paramMap.getLongMisValid("mapActivityId");
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        WzMapActivity mapActivity = cacheService.mapActivity(mapActivityId);
        List<Map<String, Object>> list = userActivityMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzUserActivity>().setSqlSelect("user_code As nickName,create_time As createTime,share_number As shareNumber").eq("map_activity_id", mapActivityId).orderBy("create_time", true));
        for (Map map : list) {
            WzUser user = cacheService.user(Long.parseLong(map.get("nickName").toString()));
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("nickName", user.getNickName());
            map.put("needShareNumber", mapActivity.getNeedShareNumber());
        }
        return Res.success(paramMap.data(list));
    }

    public Res deleteWzCoupon(ParamMap paramMap) throws Exception {
        Long couponId = paramMap.getLongMisValid("couponId");
        WzCoupon coupon = couponMapper.selectById(couponId);
        if (coupon.getStatus() != EnWzPrize.STATUS_REJECT.getIndex()) {
            return Res.fail("当前状态无法删除！");
        }
        if (coupon.getSubtype() == EnWzMapActivity.SUBTYPE_DHQ.getIndex()) {
            PfFile file = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_url", coupon.getPic()));
            if (file != null) {
                AliOssUtil.deleteObject(file.getFileUrl(), file.getType(), file.getBucketName());
                pfFileService.deleteById(file);
            }
        }
        couponMapper.deleteById(coupon);
        return Res.success();
    }

    public Res couponUsedList(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long couponId = paramMap.getLongMisValid("couponId");
        String sql = "nick_name As nickName,avatar_url As avatarUrl,scan_time As createTime";
        List<Map<String, Object>> list = userCouponMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzUserCoupon>().setSqlSelect(sql).eq("coupon_id", couponId).eq("status", EnWzPrize.COUPON_STATUS_USED.getIndex()));
        return Res.success(paramMap.data(list));
    }

    public Res couponSoldList(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long couponId = paramMap.getLongMisValid("couponId");
        String sql = "nick_name As nickName,avatar_url As avatarUrl,order_number As orderNumber";
        List<Map<String, Object>> list = couponOrderMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzCouponOrder>().setSqlSelect(sql).eq("coupon_id", couponId));
        return Res.success(paramMap.data(list));
    }


    public Res newMyAdvMapCouponList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = couponMapper.selectCount(new EntityWrapper<WzCoupon>().eq("user_code", userCode).in("status", new Integer[]{EnWzPrize.COUPON_STATUS_WaitCheck.getIndex(), EnWzPrize.COUPON_STATUS_Reject.getIndex(), EnWzPrize.COUPON_STATUS_Release.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = couponMapper.selectCount(new EntityWrapper<WzCoupon>().eq("user_code", userCode).eq("status", EnWzPrize.COUPON_STATUS_End.getIndex()));
        paramMap.put("finishNumber", finishNumber);//过期

        EntityWrapper<WzCoupon> e = new EntityWrapper<WzCoupon>();
        if (status == 1) {//进行中
            e.in("status", new Integer[]{EnWzPrize.COUPON_STATUS_WaitCheck.getIndex(), EnWzPrize.COUPON_STATUS_Reject.getIndex(), EnWzPrize.COUPON_STATUS_Release.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzPrize.COUPON_STATUS_End.getIndex());
        }

        String sql = "use_type As useType,adv_map_id As advMapId,coupon_id As couponId,benefit,status,begin_time As beginTime,end_time As endTime,pic,price,merchant_name As name,logo";
        List<Map<String, Object>> couponList = couponMapper.selectMaps(e.setSqlSelect(sql).eq("user_code", userCode));
        for(Map<String, Object> map : couponList){
            WzAdvMap advMap = advMapMapper.selectById(Long.parseLong(map.get("advMapId").toString()));
            if(StringUtils.isBlank(map.get("logo").toString())){
                map.put("logo",advMap.getLogo());
            }
            if(StringUtils.isBlank(map.get("name").toString())){
                map.put("name",advMap.getName());
            }
            map.put("adCode",advMap.getAdCode());
            int usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("coupon_id",Long.parseLong(map.get("couponId").toString())).eq("type",EnWzCoupon.TYPE_OriginalPrice.getIndex()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
            map.put("usedNumber",usedNumber);
            map.put("profit",Integer.parseInt(map.get("price").toString())*usedNumber);
            if(StringUtils.isBlank(map.get("pic").toString())){
                map.put("pic",advMap.getAvatarUrl());
            }
            int waitDeliveryNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().setSqlSelect(sql).eq("coupon_id", Long.parseLong(map.get("couponId").toString())).eq("status",EnWzCoupon.STATUS_Normal.getIndex()));
            map.put("waitDeliveryNumber",waitDeliveryNumber);
            //拼单券
            String mapMergeSql="limit_number As limitNumber,total_number As totalNumber,map_merge_id AS mapMergeId,status,merge_price AS mergePrice,sales,begin_time As beginTime,end_time As endTime,reject_remark AS rejectRemark";
            List<Map<String,Object>> mapMergeList=mapMergeMapper.selectMaps(new EntityWrapper<WzMapMerge>().setSqlSelect(mapMergeSql).eq("coupon_id", Long.parseLong(map.get("couponId").toString())).in("status", Arrays.asList(EnWzMapMerge.STATUS_CHECKING.getIndex(), EnWzMapMerge.STATUS_REJECT.getIndex(),EnWzMapMerge.STATUS_RELEASE.getIndex(), EnWzMapMerge.STATUS_END.getIndex(),EnWzMapMerge.STATUS_Down.getIndex())));
            for(Map<String,Object> mapMergeMap:mapMergeList){
                int joinNumber = userMergeDetailMapper.selectCount(new EntityWrapper<WzUserMergeDetail>().eq("map_merge_id",Long.parseLong(mapMergeMap.get("mapMergeId").toString())).in("status",new Integer[]{EnWzMapMerge.UserMapMergeDetail_OnGoing.getIndex(),EnWzMapMerge.UserMapMergeDetail_Finish.getIndex()}));
                usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("map_merge_id",mapMergeMap.get("mapMergeId").toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
                mapMergeMap.put("profit",usedNumber*Integer.parseInt(mapMergeMap.get("mergePrice").toString()));
                mapMergeMap.put("joinNumber",joinNumber);
                mapMergeMap.put("usedNumber",usedNumber);
                mapMergeMap.put("price",map.get("price"));
            }
            map.put("mapMergeList",mapMergeList);

            //返利券
            String mapRebateSql="limit_number As limitNumber,map_rebate_id As mapRebateId,status,rebate_price AS rebatePrice,need_share_number As needShareNumber,sales,begin_time As beginTime,end_time As endTime,reject_remark AS rejectRemark";
            List<Map<String,Object>> mapRebateList = mapRebateMapper.selectMaps(new EntityWrapper<WzMapRebate>().setSqlSelect(mapRebateSql).eq("type",EnWzMapRebate.Type_My_Coupon.getIndex()).eq("coupon_id", Long.parseLong(map.get("couponId").toString())).in("status", Arrays.asList(EnWzMapRebate.STATUS_CHECKING.getIndex(), EnWzMapRebate.STATUS_REJECT.getIndex(), EnWzMapRebate.STATUS_RELEASE.getIndex(), EnWzMapRebate.STATUS_Down.getIndex(), EnWzMapRebate.STATUS_END.getIndex())));
            for(Map<String,Object> mapRebateMap:mapRebateList){
                int joinNumber = userRebateMapper.selectCount(new EntityWrapper<WzUserRebate>().eq("map_rebate_id",Long.parseLong(mapRebateMap.get("mapRebateId").toString())).ne("status",EnWzMapRebate.USERREBATE_STATUS_Wait_Pay.getIndex()));
                usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("map_rebate_id",mapRebateMap.get("mapRebateId").toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
                List<Map<String, Object>> profit = userCouponMapper.selectMaps(Condition.create().setSqlSelect("sum(price) As profit").eq("map_rebate_id",Long.parseLong(mapRebateMap.get("mapRebateId").toString())).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
                if(profit.get(0) == null){
                    mapRebateMap.put("profit",0);
                }else{
                    mapRebateMap.put("profit",profit.get(0).get("profit"));
                }
                mapRebateMap.put("usedNumber",usedNumber);
                mapRebateMap.put("price",map.get("price"));
                mapRebateMap.put("joinNumber",joinNumber);
            }
            map.put("mapRebateList",mapRebateList);

            //券库券
            String marketSql="coupon_market_id AS couponMarketId,status,market_price AS marketPrice,total_number As totalNumber,reject_remark AS rejectRemark";
            List<Map<String,Object>> couponMarketList = couponMarketMapper.selectMaps(new EntityWrapper<WzCouponMarket>().setSqlSelect(marketSql).eq("coupon_id", Long.parseLong(map.get("couponId").toString())).in("status", Arrays.asList(EnWzCouponMarket.STATUS_CHECKING.getIndex(), EnWzMapMerge.STATUS_REJECT.getIndex(), EnWzMapMerge.STATUS_END.getIndex(), EnWzMapMerge.STATUS_RELEASE.getIndex())));
            for(Map<String,Object> couponMarketMap:couponMarketList){
                usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("coupon_market_id",Long.parseLong(couponMarketMap.get("couponMarketId").toString())).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
                couponMarketMap.put("profit",Integer.parseInt(couponMarketMap.get("marketPrice").toString()) * usedNumber);
            }
            map.put("couponMarketList",couponMarketList);
        }
        paramMap.put("list", couponList);
        return Res.success(paramMap);
    }

    public Res mapRebateList(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();

        String sql = "map_merge_id As mapMergeId,adv_map_id As adv_map_id,coupon_id As couponId,merchant_name As merchantName";
        List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzMapRebate>().setSqlSelect(sql).eq("user_code",userCode).eq("type", EnWzMapRebate.Type_Other_Coupon.getIndex()));
        for (Map map : mapRebateList) {
            //已卖出数量
            List<Object> soldNumber = couponOrderMapper.selectObjs(new EntityWrapper<WzCouponOrder>().setSqlSelect("ifnull(sum(order_number),0)").eq("coupon_id", map.get("couponId").toString()));
            if (Integer.parseInt(soldNumber.get(0).toString()) < Integer.parseInt(map.get("stock").toString())) {
                WzAdvMap advMap = cacheService.advMap(Long.parseLong(map.get("advMapId").toString()));
                map.put("latitude",advMap.getLatitude());
                map.put("longitude",advMap.getLongitude());
                map.put("name", advMap.getName());
                map.put("logo", advMap.getLogo());
                map.put("soldNumber", soldNumber.get(0));
            }
        }
        return Res.success(paramMap.data(mapRebateList));
    }

    public Res newMyAdvMapAdvList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = advMapper.selectCount(new EntityWrapper<WzAdv>().eq("user_code", userCode).in("status", new Integer[]{EnWzAdv.STATUS_RELEASE_no.getIndex(), EnWzAdv.STATUS_RELEASE_yes.getIndex()}));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = advMapper.selectCount(new EntityWrapper<WzAdv>().eq("user_code", userCode).eq("status", EnWzAdv.STATUS_Settlement.getIndex()).in("subtype", new Integer[]{EnWzAdv.SUBTYPE_ADV.getIndex(), EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()}));
        paramMap.put("finishNumber", finishNumber);//过期
        //广告红包
        EntityWrapper<WzAdv> e = new EntityWrapper<WzAdv>();
        e.eq("user_code", userCode).in("subtype", new Integer[]{EnWzAdv.SUBTYPE_ADV.getIndex(), EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()}).orderBy("release_time",false);
        if (status == 1) {//发布中
            e.in("status", new Integer[]{EnWzAdv.STATUS_RELEASE_no.getIndex(), EnWzAdv.STATUS_RELEASE_yes.getIndex()});
        } else if (status == 2) {//已到期
            e.eq("status", EnWzAdv.STATUS_Settlement.getIndex());
        }
        String sql = "share_reward As shareReward,share_average_reward As shareAverageReward,adv_id As advId,adv_map_id As advMapId,title,avatar_url As logo,nick_name As name,cover_url As coverUrl,subtype,status,total_number As totalNumber,push_number As pushNumber,begin_time As beginTime,end_time As endTime";
        List<Map<String, Object>> advList = advMapper.selectMaps(e.setSqlSelect(sql));

        for (Map<String, Object> map : advList) {
            //参与分享人数
            int shareNumber = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",map.get("advId")));
            map.put("shareNumber",shareNumber);
            //可参与分享总人数
            if(Integer.parseInt(map.get("shareAverageReward").toString()) == 0){
                map.put("shareUserNumber",0);
            }else{
                map.put("shareUserNumber",Integer.parseInt(map.get("shareReward").toString())/Integer.parseInt(map.get("shareAverageReward").toString()));
            }
            if (!map.get("logo").toString().substring(0, 4).equals("http")) {
                map.put("logo", "http://oss.50waizhuan.com/" + map.get("logo"));
            }
            map.put("totalshareNumber", "0");//有效点击数
            map.put("totalclickNumber", "0");//总点击数
            List<Map<String, Object>> totalshareNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id", Long.parseLong(map.get("advId").toString())));
            List<Map<String, Object>> totalclickNumber = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(click_number) As totalclickNumber").eq("adv_id", Long.parseLong(map.get("advId").toString())));
            if (totalshareNumber.get(0) != null) {
                map.put("totalshareNumber", Integer.parseInt(totalshareNumber.get(0).get("totalshareNumber").toString()) + Integer.parseInt(map.get("pushNumber").toString()));
            }
            if (totalclickNumber.get(0) != null) {
                map.put("totalclickNumber", Integer.parseInt(totalclickNumber.get(0).get("totalclickNumber").toString()) + Integer.parseInt(map.get("pushNumber").toString()));
            }
        }
        paramMap.put("list", advList);
        return Res.success(paramMap);
    }

}
